//
//  AKClient.m
//  AKPZ
//
//  Created by Lexi on 16-3-14.
//  Copyright (c) 2016年 aikangpeizhen. All rights reserved.
//

#import "AKClient.h"
#import "AKRequestManager.h"
#import "SSKeychain.h"

@implementation AKClient

+ (id)sharedInstance {
    static id sharedInstance = nil;
    if (nil == sharedInstance) {
        @synchronized([AKClient class]) {
            if (nil == sharedInstance) {
                sharedInstance = [[AKClient alloc] init];
            }
        }
    }
    return sharedInstance;
}

- (void)autoLogin {
    AKRequestManager *loginManager = [AKRequestManager managerUCorDC:UC_URI];   //登录无需token
    NSString *account = [[AKUserDefaults sharedInstance] phone];
    NSString *pwd = [[AKUserDefaults sharedInstance] pwd];
    DLog(@"account:%@ pwd:%@", account, pwd);
    if (account && pwd) {   //如果之前有记录phone和密码, 就进行自动登录, 否则的话直接返回
        
    } else {
        return;
    }
    NSMutableDictionary *params = [loginManager defaultParameter];
    [params setObject:account forKey:@"tel"];
    [params setObject:pwd forKey:@"password"];
    [params setObject:[[AKUserDefaults sharedInstance] dc] forKey:@"dcName"];
    [loginManager.requestManager invokeMethod:LOGIN_URL withParameters:params requestId:@"1" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        DLog(@"auto login success:%@", responseObject);
        NSDictionary *responseDict = (NSDictionary *)responseObject;
        NSString *token = responseDict.token;
        [[AKUserDefaults sharedInstance] setToken:token];   //将token保存进keychain
        [self getUserByToken];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        DLog(@"auto login failed:%@", error);//在自动登录的过程中, 只打印错误日志, 不进行UI提示
        [self handleLogoutDone];
    }];
}

- (void)autoLogin:(void (^)(UserInfo *))block {
    self.loginDoneBlock = block;
    [self autoLogin];
}

//获取用户基本信息
- (void)getUserByToken {
    AKRequestManager *userManager = [AKRequestManager managerUCorDC:UC_URI];
    NSMutableDictionary *params = [userManager defaultParameter];
    [userManager.requestManager invokeMethod:GET_USER_BY_TOKEN_URL withParameters:params requestId:@"1" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        DLog(@"autoLogin getUserByToken success:%@", responseObject);
        //处理登录逻辑
        NSDictionary *responseDict = (NSDictionary *)responseObject;
        [[AKUserDefaults sharedInstance] setDc:responseDict.dc];
        [self handleLoginDone:responseDict];
        [self getTenantInfo];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        DLog(@"autoLogin getUserByToken failed:%@", error);
        [self handleLogoutDone];
    }];
}

//获取商家基本信息
- (void)getTenantInfo {
    AKRequestManager *tenantManger = [AKRequestManager manager:OPERATION_URI];
    NSMutableDictionary *params = [tenantManger defaultParameter];
    [params setObject:[[AKClient sharedInstance] loginInfo].userUID forKey:@"tenantUID"];
    [tenantManger.requestManager invokeMethod:GET_TENANT_INFO_URL withParameters:params requestId:@"1" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        DLog(@"autoLogin getTenantInfo success:%@", responseObject);
        [[AKClient sharedInstance] handleTenantDone:(NSDictionary *)responseObject];    //处理商家基本信息
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        DLog(@"autoLogin getTenantInfo failed:%@", error);
        [self handleLogoutDone];
    }];
}

- (void)handleLoginDone:(NSDictionary *)data {
    self.loginInfo = [[UserInfo alloc] init];
    _loginInfo.name = data.userName;
    _loginInfo.userType = [data.userType integerValue];
    _loginInfo.userUID = data.userUID;
}

- (void)handleTenantDone:(NSDictionary *)data {
    self.logon = YES;
    
    TenantInfo *info = [[TenantInfo alloc] init];
    info.address = data.address;
    info.area = data.area;
    info.areaCode = data.areaCode;
    info.authStatus = data.authStatus;
    info.businessEntity = data.businessEntity;
    info.businessEntityTel = data.businessEntityTel;
    info.businessLisence = data.businessLisence;
    info.businessLisencePhotoURL = data.businessLisencePhotoURL;
    info.city = data.city;
    info.cityCode = data.cityCode;
    info.dc = data.dc;
    info.dcName = data.dcName;
    info.deliveryAddress = data.deliveryAddress;
    info.email = data.email;
    info.enterpriseFullName = data.enterpriseFullName;
    info.expirationDate = data.expirationDate;
    info.groupId = data.groupId;
    info.groupPath = data.groupPath;
    info.idPhotoBackURL = data.idPhotoBackURL;
    info.idPhotoFrontURL = data.idPhotoFrontURL;
    info.identityCard = data.identityCard;
    info.industyTag = data.industyTag;
    info.industyType = data.industyType;
    info.isPhonePublic = data.isPhonePublic;
    info.isRoot = data.isRoot;
    info.lastLoginTime = data.lastLoginTime;
    info.logoURL = data.logoURL;
    info.nickName = data.nickName;
    info.partment = data.partment;
    info.password = data.password;
    info.phone = data.phone;
    info.post = data.post;
    info.province = data.province;
    info.provinceCode = data.provinceCode;
    info.qq = data.qq;
    info.registTime = data.registTime;
    info.role = [data.role integerValue];
    info.roleDes = data.roleDes;
    info.siteURL = data.siteURL;
    info.storeArea = data.storeArea;
    info.storeCount = data.storeCount;
    info.storeLayer = data.storeLayer;
    info.storeName = data.storeName;
    info.storeShareInfo = data.storeShareInfo;
    info.tel = data.tel;
    info.tenantFullName = data.tenantFullName;
    info.tenantName = data.tenantName;
    info.tenantUID = data.tenantUID;
    info.userLogoURL = data.userLogoURL;
    info.userTypeDes = data.userTypeDes;
    info.username = data.username;
    info.verificationCode = data.verificationCode;
    info.weibo = data.weibo;
    info.weixin = data.weixin;
    
    _loginInfo.tenantInfo = info;
    
    switch (info.role) {
        case UserRoleMerchantOwner: {_loginInfo.roleString = @"户主"; break;}
        case UserRoleMerchantDevice: {_loginInfo.roleString = @"设备管理员"; break;}
        case UserRoleMerchantContent: {_loginInfo.roleString = @"内容管理员"; break;}
        case UserRoleMerchantContentExamine: {_loginInfo.roleString = @"内容审核员"; break;}
        default: {_loginInfo.roleString = @"户主"; break;}
    }
    
    if (_loginDoneBlock) {
        _loginDoneBlock(_loginInfo);
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:UserLoginNotification object:nil];   //成功获取商户信息以后才算登录成功
}

- (void)handleLogoutDone {
    self.logon = NO;
    [self clearKeychain];
    [[NSNotificationCenter defaultCenter] postNotificationName:UserLogoutNotification object:nil];
}

- (void)handleServiceInfoDone:(NSDictionary *)data {
    ServiceInfo *info = [[ServiceInfo alloc] init];
    info.amount = data.amount;
    info.currentVistorCount = data.currentVistorCount;
    info.deviceCount = data.deviceCount;
    info.faultDeviceCount = data.faultDeviceCount;
    info.infoIntegrity = data.infoIntegrity;
    info.smsLeave = data.smsLeave;
    info.vistorCount = data.vistorCount;
    _loginInfo.serviceInfo = info;
}

- (void)handleProvinceArray:(NSMutableArray *)data {
    self.provinceArray = [NSMutableArray arrayWithArray:data];
}

- (void)handleIndustry:(NSMutableArray *)data {
    self.industryArray = [NSMutableArray arrayWithArray:data];
}

//清空钥匙链数据
- (void)clearKeychain {
    [SSKeychain deletePasswordForService:KEYCHAIN_SERVICE account:@"kPhone"];
    [SSKeychain deletePasswordForService:KEYCHAIN_SERVICE account:@"kPwd"];
    [SSKeychain deletePasswordForService:KEYCHAIN_SERVICE account:@"kToken"];
    [SSKeychain deletePasswordForService:KEYCHAIN_SERVICE account:@"kDc"];
}

@end
